const express = require('express');
const router = express.Router();
const { Ad } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

// 获取所有广告（公开接口）
router.get('/', async (req, res) => {
  try {
    const { position, active = true } = req.query;
    const now = new Date();
    
    const query = {
      isActive: active === 'true',
      startDate: { $lte: now },
      endDate: { $gte: now }
    };
    
    if (position) {
      query.position = position;
    }
    
    const ads = await Ad.find(query)
      .sort({ priority: -1, createdAt: -1 })
      .populate('createdBy', 'username');
    
    res.json({
      success: true,
      data: ads
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取广告失败',
      error: error.message
    });
  }
});

// 获取广告详情
router.get('/:id', async (req, res) => {
  try {
    const ad = await Ad.findById(req.params.id)
      .populate('createdBy', 'username');
    
    if (!ad) {
      return res.status(404).json({
        success: false,
        message: '广告不存在'
      });
    }
    
    res.json({
      success: true,
      data: ad
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取广告详情失败',
      error: error.message
    });
  }
});

// 创建广告（管理员）
router.post('/', auth, adminAuth, upload.single('image'), async (req, res) => {
  try {
    const {
      title,
      description,
      targetUrl,
      position,
      priority,
      startDate,
      endDate
    } = req.body;
    
    const imageUrl = req.file ? `/uploads/${req.file.filename}` : req.body.imageUrl;
    
    const ad = new Ad({
      title,
      description,
      imageUrl,
      targetUrl,
      position,
      priority: parseInt(priority) || 0,
      startDate: new Date(startDate),
      endDate: new Date(endDate),
      createdBy: req.user.id
    });
    
    await ad.save();
    await ad.populate('createdBy', 'username');
    
    res.status(201).json({
      success: true,
      message: '广告创建成功',
      data: ad
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: '创建广告失败',
      error: error.message
    });
  }
});

// 更新广告（管理员）
router.put('/:id', auth, adminAuth, upload.single('image'), async (req, res) => {
  try {
    const updates = { ...req.body };
    
    if (req.file) {
      updates.imageUrl = `/uploads/${req.file.filename}`;
    }
    
    if (updates.priority) {
      updates.priority = parseInt(updates.priority);
    }
    
    if (updates.startDate) {
      updates.startDate = new Date(updates.startDate);
    }
    
    if (updates.endDate) {
      updates.endDate = new Date(updates.endDate);
    }
    
    const ad = await Ad.findByIdAndUpdate(
      req.params.id,
      updates,
      { new: true, runValidators: true }
    ).populate('createdBy', 'username');
    
    if (!ad) {
      return res.status(404).json({
        success: false,
        message: '广告不存在'
      });
    }
    
    res.json({
      success: true,
      message: '广告更新成功',
      data: ad
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: '更新广告失败',
      error: error.message
    });
  }
});

// 删除广告（管理员）
router.delete('/:id', auth, adminAuth, async (req, res) => {
  try {
    const ad = await Ad.findByIdAndDelete(req.params.id);
    
    if (!ad) {
      return res.status(404).json({
        success: false,
        message: '广告不存在'
      });
    }
    
    res.json({
      success: true,
      message: '广告删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除广告失败',
      error: error.message
    });
  }
});

// 记录广告点击
router.post('/:id/click', async (req, res) => {
  try {
    const ad = await Ad.findByIdAndUpdate(
      req.params.id,
      { $inc: { clickCount: 1 } },
      { new: true }
    );
    
    if (!ad) {
      return res.status(404).json({
        success: false,
        message: '广告不存在'
      });
    }
    
    res.json({
      success: true,
      message: '点击记录成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '记录点击失败',
      error: error.message
    });
  }
});

// 记录广告展示
router.post('/:id/impression', async (req, res) => {
  try {
    const ad = await Ad.findByIdAndUpdate(
      req.params.id,
      { $inc: { impressionCount: 1 } },
      { new: true }
    );
    
    if (!ad) {
      return res.status(404).json({
        success: false,
        message: '广告不存在'
      });
    }
    
    res.json({
      success: true,
      message: '展示记录成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '记录展示失败',
      error: error.message
    });
  }
});

// 获取广告统计（管理员）
router.get('/stats/overview', auth, adminAuth, async (req, res) => {
  try {
    const totalAds = await Ad.countDocuments();
    const activeAds = await Ad.countDocuments({ isActive: true });
    const totalClicks = await Ad.aggregate([
      { $group: { _id: null, total: { $sum: '$clickCount' } } }
    ]);
    const totalImpressions = await Ad.aggregate([
      { $group: { _id: null, total: { $sum: '$impressionCount' } } }
    ]);
    
    res.json({
      success: true,
      data: {
        totalAds,
        activeAds,
        totalClicks: totalClicks[0]?.total || 0,
        totalImpressions: totalImpressions[0]?.total || 0
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
});

module.exports = router;